package sfx;

import gfx.Tickable;

import java.util.ArrayList;

import core.Main;
import core.Vector2;

public class SoundX implements Tickable{
	private boolean ambient;
	
	private Sound sound;
	private Vector2 source;
	private ArrayList<Sound> soundLayer;
	
	public SoundX(Sound sound, Vector2 source){
		Main.addTickable(this);
		
		if(source == null){
			ambient = true;
		}else{
			ambient = false;
			this.source = source;
		}
		
		this.sound = sound;
		soundLayer = new ArrayList<Sound>();
		
	}
	
	public void play(){
		soundLayer.add(sound);
		handleVolumes();
		soundLayer.get(soundLayer.size() - 1).play();
	}
	
	/**
	 * @param sound ID of the sound to check
	 * @return whether the sound specified in the first parameter is playing
	 */
	public boolean isPlaying(){
		for(int i = 0; i < soundLayer.size();i++){
			if(soundLayer.get(i).isPlaying()){
				return true;
			}
		}
		return false;
	}
	
	public void handleVolumes(){
		if(!ambient && (source.x >= Main.mapPos.x && source.x <= Main.mapPos.x + Main.WIDTH && source.y >= Main.mapPos.y && source.y <= Main.mapPos.y + Main.HEIGHT)){
			for(int i = 0; i < soundLayer.size();i++){
				soundLayer.get(i).setVolume(0);
			}
		}else{
			for(int i = 0; i < soundLayer.size();i++){
				soundLayer.get(i).setVolume(-1000);
			}
		}
	}

	@Override
	public void tick() {
		boolean clear = true;
		for(int i = 0;i < soundLayer.size();i++){
			if(soundLayer.get(i).isPlaying()){
				clear = false;
			}
		}
		if(clear){
			soundLayer.clear();
		}
		
		handleVolumes();
	}

	@Override
	public Vector2 getPos() {
		return null;
	}

	@Override
	public Vector2 getSize() {
		return null;
	}

	@Override
	public boolean removed() {
		return false;
	}

	@Override
	public int getID() {
		return 0;
	}
	
	
}
